package com.bzsg.rightsManagementSystem.config.security_config

import com.alibaba.fastjson.JSONObject
import org.springframework.http.MediaType
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import java.io.IOException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 改用json登陆
 */

class CustomAuthenticationFilter : UsernamePasswordAuthenticationFilter() {
    @Throws(AuthenticationException::class)
    override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse?): Authentication {
        return if (request.contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
            var authRequest: UsernamePasswordAuthenticationToken?
            try {
                request.inputStream.use {
                    val b = ByteArray(1024)
                    val len = it.read(b)
                    val message = String(b, 0, len)
                    val nameAndPassword= JSONObject.parseObject(message)
                    val userName = nameAndPassword.getString("userName")
                    val password = nameAndPassword.getString("password")
                    authRequest = UsernamePasswordAuthenticationToken(userName, password)
                }
            } catch (e: IOException) {
                e.printStackTrace()
                authRequest = UsernamePasswordAuthenticationToken("", "")
            }
            setDetails(request, authRequest)
            this.authenticationManager.authenticate(authRequest)
        } else {
            super.attemptAuthentication(request, response)
        }
    }
}